import axios from "axios";
import { ElMessage } from "element-plus";
import { useLoadStore } from '@/stores/counter';
import VueCookie from 'vue-cookie' // 引入cookie插件 获取cookie 
import router from '@/router'
const loadStore = useLoadStore();
export const _axios = axios.create({
  baseURL: "http://127.0.0.1:8080"
})
// export 暴露     这是一个函数
export const request = (url, method, params, callback) => {
    const axiosConfig = {
      url,
      method
    }
    const token = VueCookie.get('token') // 获取token
    if (token) {
      _axios.defaults.headers.common['token'] = token
    }
    /**   老师说
     * get 请求 参数是json形式
     * post请求 参数是转换为 FormData 对象
     */
    if (method === 'post') {
      const formData = new FormData()
      for (const key in params) {
        // 将键值对添加到 FormData 对象中
        formData.append(key, params[key])
      }
      axiosConfig.data = formData // post请求 FormData
    } else {
      axiosConfig.params = params // get请求
    }
    loadStore.open()
    _axios.request(axiosConfig).then(response => {
      if (response.data.code === 200) {
        if (response.data.message) {
          ElMessage.success(response.data.message) //提示信息
        }
        callback(response.data.content) //回调函数
      } else {
        ElMessage.error(response.data.message)
        if (response.data.code === 401) { // 登录有问题 返回登录页面
          router.push('/login')
        }
      }
    }).catch(error => {
      console.dir(error)
    }).finally(() => {
      loadStore.close()
    })
  }
  
export const get = (url, params, callback) => { request(url, 'get', params, callback) }
export const post = (url, params, callback, formobj = null) => {
  if (formobj) {
    formobj.value.validate(valid => { //调用其 validate 方法进行表单验证
      if (valid) {
        request(url, 'post', params, callback)
      }
    })
  } else {
    request(url, 'post', params, callback)
  }
}



